<?php
/**
 * 图像生成
 * 
 * $Id: gdplus.php 122 2010-05-28 10:05:16Z Administrator $
 * $Revision: 122 $
 * $Author: Administrator $
 * $Date: 2010-05-28 18:05:16 +0800 (星期五, 28 五月 2010) $
 * @author glzaboy<glzaboy@163.com>
 * @package fastlib
 * @subpackage classes
 * @copyright 2005-2010 (c) glzaboy
 */
if (! defined ( '__FASTLIB__' )) {
	if (__DEBUG__) {
		die ( sprintf ( 'Forbidden 403 at file %s on line %d', __FILE__, __LINE__ ) );
	} else {
		die ( 'Forbidden 403' );
	}
}
/**
 * 高级图像生成
 *
 * 采用独特的多文件对象，可以将多张图合成一张，
 * 可以生成缩略图片,同时可以使用滤镜效果。
 *
 * @author glzaboy <glzaboy@163.com>
 */
class gdplus {
	/**
	 * GD版本
	 *
	 * @return unknown
	 */
	private $gdVersion = null;
	/**
	 * 色彩句柄
	 *
	 * @var array
	 */
	private $hColor = array ();
	/**
	 * LOAD进来的图片资源
	 *
	 * array(
	 * 'name'=>array('handel'=>handel,'width'=>'')
	 * )
	 *
	 * @var array
	 */
	private $hImageReSource = array ();
	/**
	 * getimagesize返回的type对应的文件类型
	 *
	 * @var array
	 */
	private $imageTypes = array (1 => 'GIF', 2 => 'JPG', 3 => 'PNG', 4 => 'SWF', 5 => 'PSD', 6 => 'BMP', 7 => 'TIFF', //intel byte order
8 => 'TIFF', //motorola byte order
9 => 'JPC', 10 => 'JP2', 11 => 'JPX', 12 => 'JB2', 13 => 'SWC', 14 => 'IFF', 15 => 'WBMP', 16 => 'XBM' );
	/**
	 * 生成真彩色的图片
	 *
	 * @var bool
	 */
	private $bTrueColor = false;
	/**
	 * 生成真彩色的图片
	 *
	 * @param bool $bTrueColor 是否为真彩色，默认为假
	 */
	public function __construct($bTrueColor = false) {
		$this->gdVersion = GD_VERSION;
		$this->bTrueColor = $bTrueColor;
	}
	public function __destruct() {
		$this->destory ();
		$this->gdVersion = null;
	}
	/**
	 * 释放所有图片资源
	 * 
	 * 如何指定资源名称那么只释放指定的资源，否则释放所有的图片资源
	 *
	 * @param String $handel 要释放的资源名称 
	 */
	public function destory($handel = null) {
		if ($handel == null) {
			if (is_array ( $this->hImageReSource )) {
				foreach ( $this->hImageReSource as $k => $v ) {
					imagedestroy ( $v ['handel'] );
					unset ( $this->hImageReSource [$k] );
				}
				$this->hImageReSource = array ();
			}
		}
	}
	/**
	 * 创建要输出的图片
	 *
	 * @param int $maxWidth 最大图片宽度
	 * @param int $maxHeight 最大图片高度
	 * @param array $background 图片背景
	 * @return bool 是否成功
	 */
	public function createImage($maxWidth, $maxHeight, $background = array(0,0,0)) {
		$resourceName = "mast";
		if ($this->bTrueColor) {
			$this->hImageReSource [$resourceName] ['handel'] = @imagecreatetruecolor ( $maxWidth, $maxHeight );
			if (! $this->hImageReSource [$resourceName] ['handel']) {
				$this->hImageReSource [$resourceName] ['handel'] = @imagecreate ( $maxWidth, $maxHeight );
			}
		} else {
			$this->hImageReSource [$resourceName] ['handel'] = @imagecreate ( $maxWidth, $maxHeight );
		}
		if (count ( $background ) != 3) {
			$background = array (0, 0, 0 );
		}
		array_unshift ( $background, $this->hImageReSource [$resourceName] ['handel'] );
		$this->hColor ['background'] = call_user_func_array ( "imagecolorallocate", $background );
		imagefill ( $this->hImageReSource [$resourceName] ['handel'], 0, 0, $this->hColor ['background'] );
		return $this->hImageReSource [$resourceName] ['handel'];
	}
	/**
	 * 读取图片资源
	 *
	 * @param String $imageFile 图片地址或数据
	 * @param String $resourceName 资源名称 
	 * @return unknown
	 */
	public function loadImage($imageFile, $resourceName = null) {
		if ($resourceName == null) {
			if ($this->hImageReSource [$resourceName] ['handel']) {
				imagedestroy ( $this->hImageReSource ['mast'] ['handel'] );
				unset ( $this->hImageReSource ['mast'] ['handel'] );
			}
			$resourceName = 'mast';
		}
		if (is_String ( $imageFile )) {
			if (file_exists ( $imageFile )) {
				$imageSize = getimagesize ( $imageFile );
				if ($imageSize) {
					$imageSize ['type'] = $imageSize [2];
				} else {
					return false;
				}
				switch (strtolower ( $this->imageTypes [$imageSize ['type']] )) {
					case "gif" :
						if (! $imageSize ['handel'] = @imagecreatefromgif ( $imageFile )) {
							return false;
						}
						return $this->hImageReSource [$resourceName] = $imageSize;
						break;
					case "jpg" :
						if (! $imageSize ['handel'] = @imagecreatefromjpeg ( $imageFile )) {
							return false;
						}
						return $this->hImageReSource [$resourceName] = $imageSize;
						break;
					case "png" :
						if (! $imageSize ['handel'] = @imagecreatefrompng ( $imageFile )) {
							return false;
						}
						return $this->hImageReSource [$resourceName] = $imageSize;
						break;
					case "xbm" :
						if (! $imageSize ['handel'] = @imagecreatefromxbm ( $imageFile )) {
							return false;
						}
						return $this->hImageReSource [$resourceName] = $imageSize;
						break;
					case "wbmp" :
						if (! $imageSize ['handel'] = @imagecreatefromwbmp ( $imageFile )) {
							return false;
						}
						return $this->hImageReSource [$resourceName] = $imageSize;
						break;
					case "bmp" :
						if (! $imageSize ['handel'] = $this->bmp2gd ( file_get_contents ( $imageFile ) )) {
							return false;
						}
						return $this->hImageReSource [$resourceName] = $imageSize;
						break;
					default :
						return false;
						break;
				}
			} else {
				return $this->hImageReSource [$resourceName] ['handel'] = imagecreatefromstring ( $imageFile );
			}
		}
		return false;
	}
	/**
	 * 读取图片资源
	 *
	 * @param String $imageFile 图片地址或数据
	 * @param String $resourceName 资源名称 
	 * @return unknown
	 */
	/**
	 * 读取nfo文件并转换为图片资源
	 *
	 * @param String $fileName nfo文件地址
	 * @param String $resourceName 资源名称 
	 * @param array $fontcolor 字符色彩RGB格式的数组
	 * @param array $bgcolor 背景色彩RGB格式的数组
	 * @return unknown
	 */
	public function loadnfo($fileName, $resourceName = null, $fontcolor = null, $bgcolor = null) {
		if ($resourceName == null) {
			if ($this->hImageReSource [$resourceName] ['handel']) {
				imagedestroy ( $this->hImageReSource ['mast'] ['handel'] );
				unset ( $this->hImageReSource ['mast'] ['handel'] );
			}
			$resourceName = 'mast';
		}
		if (! file_exists ( $fileName )) {
			return false;
		}
		$nfodata = @file ( $fileName );
		if (! $nfodata) {
			return false;
		}
		$nfocfg = array ();
		$nfocfg ['width'] = 640;
		$nfocfg ['font'] = __FASTSYSTEM__ . 'font/OEM_DOS_Std.TTF';
		$nfocfg ['fontsize'] = 10; //字型大小
		$nfocfg ['space'] = 13; //行间距
		$nfocfg ['left'] = 1; //行间距
		if ($this->bTrueColor) {
			$this->hImageReSource [$resourceName] ['handel'] = imagecreatetruecolor ( $nfocfg ['width'], count ( $nfodata ) * $nfocfg ['space'] );
		} else {
			$this->hImageReSource [$resourceName] ['handel'] = imagecreate ( $nfocfg ['width'], count ( $nfodata ) * $nfocfg ['space'] );
		}
		if (count ( $fontcolor ) != 3) {
			$fontcolor = array (180, 180, 180 );
		}
		array_unshift ( $fontcolor, $this->hImageReSource [$resourceName] ['handel'] );
		$nfocfg ['fontcolor'] = call_user_func_array ( "imagecolorallocate", $fontcolor );
		if (count ( $bgcolor ) != 3) {
			$bgcolor = array (0, 0, 128 );
		}
		array_unshift ( $bgcolor, $this->hImageReSource [$resourceName] ['handel'] );
		$nfocfg ['bgcolor'] = call_user_func_array ( "imagecolorallocate", $bgcolor );
		imagefill ( $this->hImageReSource [$resourceName] ['handel'], 0, 0, $nfocfg ['bgcolor'] );
		$pheight = 0;
		for($i = 0; $i < count ( $nfodata ); $i ++) {
			$pheight += $nfocfg ["space"];
			imagettftext ( $this->hImageReSource [$resourceName] ['handel'], $nfocfg ["fontsize"], 0, $nfocfg ["left"], $pheight, $nfocfg ['fontcolor'], $nfocfg ['font'], $this->nfoformat ( $nfodata [$i] ) );
		}
		return true;
	}
	/**
	 * 转换nfo文字为utf8格式
	 *
	 * @param string $text 字符
	 * @return string 转换后的字符
	 */
	private function nfoformat($text) {
		static $codeTable = null;
		if (is_null ( $codeTable )) {
			$codeTable = array ();
			$tmp = file ( __FASTSYSTEM__ . 'driver/etc/8859-2.TXT' );
			while ( false != (list ( , $value ) = each ( $tmp )) ) {
				$codeTable [hexdec ( substr ( $value, 0, 4 ) )] = hexdec ( substr ( $value, 5, 6 ) );
			}
			unset ( $tmp );
		}
		if (! trim ( $text )) { //空行
			return $text;
		}
		$ret = '';
		while ( $text ) {
			// 提取 $text 的第一个字符，并且将该字符的10进制值赋予 $num
			$num = ord ( substr ( $text, 0, 1 ) );
			// 查找 $num 在unicode table中的影射值
			$num = $codeTable [$num];
			// 将获取影射的10进制后，经转换所得到的的字符追加到等待返回的变量中
			switch ($num) {
				case $num < 128 :
					$ret .= chr ( $num );
					break;
				case $num < 1024 :
					$ret .= chr ( ($num >> 6) + 192 ) . chr ( ($num & 63) + 128 );
					break;
				case $num < 32768 :
					$ret .= chr ( ($num >> 12) + 224 ) . chr ( (($num >> 6) & 63) + 128 ) . chr ( ($num & 63) + 128 );
					break;
				case $num < 2097152 :
					$ret .= chr ( $num >> 18 + 240 ) . chr ( (($num >> 12) & 63) + 128 ) . chr ( ($num >> 6) & 63 + 128 ) . chr ( $num & 63 + 128 );
					break;
			}
			// 去除 $parameter 的第一个字符
			$text = substr ( $text, 1, strlen ( $text ) );
		}
		// 返回经过转换的字符串变量
		return $ret;
	}
	/**
	 * 合并两个图片
	 *
	 * @param string $hDestName 目图片名称
	 * @param string $hSourceName 源图片名称
	 * @param int $pos 定位0随机，其余按手机上键位排布
	 * @param int $transparent 透明度
	 * @param array $point 当$pos为-1时合并的目标图片坐标默认array('x'=>0,'y'=>0);
	 */
	public function merge($hDestName, $hSourceName, $pos = 0, $transparent = 100, $point = array('x'=>0,'y'=>0)) {
		$hDestName = $hDestName ? $hDestName : 'mast';
		$iDest = $this->getSize ( $hDestName );
		$iSource = $this->getSize ( $hSourceName );
		$sPos = new stdClass ();
		switch ($pos) {
			case - 1 : //指定
				$sPos->x = $point [x] < 0 ? 0 : $iDest->width - $iSource->width < $point [x] ? $iDest->width - $iSource->width : $point [x];
				$sPos->y = $point [y] < 0 ? 0 : $iDest->height - $iSource->height < $point [y] ? $iDest->height - $iSource->height : $point [y];
				break;
			case 0 : //随机
				$sPos->x = rand ( 0, $iDest->width - $iSource->width );
				$sPos->y = rand ( 0, $iDest->height - $iSource->height );
				break;
			case 1 : //左上
				$sPos->x = 0;
				$sPos->y = 0;
				break;
			case 2 : //中上
				$sPos->x = ($iDest->width - $iSource->width) / 2;
				$sPos->y = 0;
				break;
			case 3 : //右上
				$sPos->x = ($iDest->width - $iSource->width);
				$sPos->y = 0;
				break;
			case 4 : //左中
				$sPos->x = 0;
				$sPos->y = ($iDest->height - $iSource->height) / 2;
				break;
			case 5 : //中中
				$sPos->x = ($iDest->width - $iSource->width) / 2;
				$sPos->y = ($iDest->height - $iSource->height) / 2;
				break;
			case 6 : //右中
				$sPos->x = ($iDest->width - $iSource->width);
				$sPos->y = ($iDest->height - $iSource->height) / 2;
				break;
			case 7 : //左下
				$sPos->x = 0;
				$sPos->y = ($iDest->height - $iSource->height);
				break;
			case 8 : //中下
				$sPos->x = ($iDest->width - $iSource->width) / 2;
				$sPos->y = ($iDest->height - $iSource->height);
				break;
			case 9 : //右下
				$sPos->x = ($iDest->width - $iSource->width);
				$sPos->y = ($iDest->height - $iSource->height);
				break;
			default :
				break;
		}
		return imagecopymergegray ( $this->hImageReSource [$hDestName] ['handel'], $this->hImageReSource [$hSourceName] ['handel'], $sPos->x, $sPos->y, 0, 0, $iSource->width, $iSource->height, $transparent );
	}
	/**
	 * 旋转图片对象
	 *
	 * @param string $hDestName 目图片名称
	 * @param int $angle 旋转角度
	 * @param array $bgColor 指定了旋转后没有覆盖到的部分的颜色
	 * @param bool $transparent 透明色会被忽略
	 * @return unknown
	 */
	public function rotate($hDestName, $angle, $bgColor = null, $transparent = true) {
		$hDestName = $hDestName ? $hDestName : 'mast';
		if (is_array ( $bgColor ) && count ( $bgColor ) == 3) {
			$picColor = $bgColor;
			$bgColor = true;
		} else {
			$picColor = array (0, 0, 255 ); //蓝色
			$bgColor = false;
		}
		array_unshift ( $picColor, $this->hImageReSource [$hDestName] ['handel'] );
		$picColor = call_user_func_array ( "imagecolorallocate", $picColor );
		$handel = imagerotate ( $this->hImageReSource [$hDestName] ['handel'], $angle, $picColor, $transparent );
		imagedestroy ( $this->hImageReSource [$hDestName] ['handel'] );
		$this->hImageReSource [$hDestName] ['handel'] = $handel;
		if (! $bgColor) {
			imagecolortransparent ( $this->hImageReSource [$hDestName] ['handel'], $picColor );
		}
		return true;
	}
	/**
	 * 增加文件到图片资源上
	 *
	 * @param string $hDestName 目图片名称
	 * @param string $text 文字
	 * @param array $textColor 色彩
	 * @param int $x 文字x位置
	 * @param int $y 文字y位置
	 * @param int $size 文字大小
	 * @param int $angle 文字角度
	 * @param string $fontFile 字体文件名
	 */
	public function drawText($hDestName, $text, $textColor = array(0,0,0), $x = 0, $y = 0, $size = 10, $angle = 0, $fontFile = "OEM_DOS_Std.TTF") {
		$hDestName = $hDestName ? $hDestName : 'mast';
		if (count ( $textColor ) != 3) {
			$picColor = array (0, 0, 0 ); //黑色
		} else {
			$picColor = $textColor;
		}
		array_unshift ( $picColor, $this->hImageReSource [$hDestName] ['handel'] );
		$font = $this->getFont ( $fontFile );
		$text = iconv ( iconv_get_encoding ( $text ), 'UTF-8', $text );
		$fbox = imagettfbbox ( $size, $angle, $font, $text );
		imagettftext ( $this->hImageReSource [$hDestName] ['handel'], $size, $angle, $x - $fbox [6], $y - $fbox [7], call_user_func_array ( "imagecolorallocate", $picColor ), $font, $text );
		unset ( $fbox );
	}
	/**
	 * 返回字体路径
	 *
	 * @param string $fontFile 字体文件名
	 * @return string 完整的字体路径
	 */
	private function getFont($fontFile) {
		if (file_exists ( __FASTSYSTEM__ . 'font/' . $fontFile )) {
			return __FASTSYSTEM__ . 'font/' . $fontFile;
		} else {
			return __FASTSYSTEM__ . 'font/OEM_DOS_Std.TTF';
		}
	}
	/**
	 * 翻转图片对象
	 *
	 *
	 * @param string $hDestName 目图片名称
	 * @param bool $direction 水平或垂直旋转1垂直0水平
	 * @return true
	 */
	public function flip($hDestName, $direction) {
		$Destsize = $this->getSize ( $hDestName );
		$hNew = imagecreatetruecolor ( $Destsize->width, $Destsize->height );
		imagealphablending ( $hNew, true );
		if ($direction) {
			for($y = 0; $y < $Destsize->height; ++ $y) {
				imagecopymerge ( $hNew, $this->hImageReSource [$hDestName] ['handel'], 0, $Destsize->height - $y - 1, 0, $y, $Destsize->width, 1, 100 );
			}
		} else {
			for($x = 0; $x < $Destsize->width; ++ $x) {
				imagecopymerge ( $hNew, $this->hImageReSource [$hDestName] ['handel'], $Destsize->width - $x - 1, 0, $x, 0, 1, $Destsize->height, 100 );
			}
		}
		imagecopyresized ( $this->hImageReSource [$hDestName] ['handel'], $hNew, 0, 0, 0, 0, $Destsize->width, $Destsize->height, $Destsize->width, $Destsize->height );
		imagedestroy ( $hNew );
		return true;
	}
	/**
	 * 对图像对象使用过滤器
	 *
	 * 本函数依靠imagefilter
	 * IMG_FILTER_NEGATE ：将图像中所有颜色反转。 
	 * IMG_FILTER_GRAYSCALE ：将图像转换为灰度的。
	 * IMG_FILTER_BRIGHTNESS ：改变图像的亮度。用 arg1 设定亮度级别。
	 * IMG_FILTER_CONTRAST ：改变图像的对比度。用 arg1 设定对比度级别。
	 * IMG_FILTER_COLORIZE ：与 IMG_FILTER_GRAYSCALE 类似，不过可以指定颜色。
	 * 用 arg1 ，arg2 和 arg3 分别指定 red ，blue 和 green 。每种颜色范围是 0 到 255。
	 * IMG_FILTER_EDGEDETECT ：用边缘检测来突出图像的边缘。
	 * IMG_FILTER_EMBOSS ：使图像浮雕化。
	 * IMG_FILTER_GAUSSIAN_BLUR ：用高斯算法模糊图像。
	 * IMG_FILTER_SELECTIVE_BLUR ：模糊图像。
	 * IMG_FILTER_MEAN_REMOVAL ：用平均移除法来达到轮廓效果。
	 * IMG_FILTER_SMOOTH ：使图像更柔滑。用 arg1 设定柔滑级别。 
	 *
	 *
	 * @param string $hDestName 资源图像名称
	 * @param array $filterType imagefilter除第一个参数后的数组
	 * @return unknown
	 */
	public function filter($hDestName, $filterType = null) {
		if (is_array ( $filterType )) {
			array_unshift ( $filterType, $this->hImageReSource [$hDestName] ['handel'] );
			return call_user_func_array ( 'imagefilter', $filterType );
		} else {
			return false;
		}
	}
	/**
	 * 从图片资源$hSourceName中取指定区域合并到$hDestName图片的指定区域
	 * 并使得取得的区域放大或缩小适应$hDestName区域大小，适应方法有0按比
	 * 你缩放，1拉伸填充指定的目标大小区，2在指定的大小内居中
	 *
	 * @param string $hDestName 目图片名称
	 * @param string $hSourceName 源图片名称
	 * @param int $iDestx 合并后的x轴
	 * @param int $iDesty 合并后的y轴
	 * @param int $iDestw 合并后的最大宽
	 * @param int $iDesth 合并后的最大高
	 * @param int $iSourcex 取资源x轴开始合并
	 * @param int $iSourcey 取资源y轴开始合并
	 * @param int $iSourcew 取资源宽合并
	 * @param int $iSourceh 取资源高合并
	 * @param int $iMode 合并模式0按比你缩放，1拉伸填充指定的目标大小区，2在指定的大小内居中
	 */
	public function resizeTo($hDestName, $hSourceName, $iDestx, $iDesty, $iDestw, $iDesth, $iSourcex, $iSourcey, $iSourcew, $iSourceh, $iMode = 0) {
		$hDestName = $hDestName ? $hDestName : 'mast';
		$oDest = $this->getSize ( $hDestName );
		$oSource = $this->getSize ( $hSourceName );
		/**
		 * 保证起始点在图片范围内
		 */
		$iDestx = $iDestx % $oDest->width;
		$iDesty = $iDesty % $oDest->height;
		$iSourcex = $iSourcex % $oSource->width;
		$iSourcey = $iSourcey % $oSource->height;
		if ($iDestw == - 1) {
			$iDestw = $oDest->width - $iDestx;
		}
		if ($iDesth == - 1) {
			$iDesth = $oDest->height - $iDesty;
		}
		if ($iDestw + $iDestx > $oDest->width) {
			$iDestw = $oDest->width - $iDestx;
		}
		if ($iDesth + $iDesty > $oDest->height) {
			$iDesth = $oDest->height - $iDesty;
		}
		$resizeAgrv = array ();
		array_push ( $resizeAgrv, $this->hImageReSource [$hDestName] ['handel'] );
		array_push ( $resizeAgrv, $this->hImageReSource [$hSourceName] ['handel'] );
		if ($iMode == 1) {
			if ($iSourcew == - 1) {
				$iSourcew = $oSource->width - $iSourcex;
			}
			if ($iSourceh == - 1) {
				$iSourceh = $oSource->height - $iSourcey;
			}
		} elseif ($iMode == 0) {
			if ($iSourcew == - 1) {
				$iSourcew = $oSource->width - $iSourcex;
			}
			if ($iSourceh == - 1) {
				$iSourceh = $oSource->height - $iSourcey;
			}
			if ($iDestw == - 1) {
				$iDestw = $oDest->width - $iDestx;
			}
			if ($iDesth == - 1) {
				$iDesth = $oDest->height - $iDesty;
			}
			if (($iDestw / $iDesth) >= ($oSource->width / $oSource->height)) {
				$iDestw = ($oSource->width / $oSource->height) * $iDesth;
			} else {
				$iDesth = (($oSource->height / $oSource->width)) * $iDestw;
			}
		} elseif ($iMode == 2) {
			if ($iSourcew == - 1) {
				$iSourcew = $oSource->width - $iSourcex;
			}
			if ($iSourceh == - 1) {
				$iSourceh = $oSource->height - $iSourcey;
			}
			if ($iDestw == - 1) {
				$iDestw = $oDest->width - $iDestx;
			}
			if ($iDesth == - 1) {
				$iDesth = $oDest->height - $iDesty;
			}
			if (($iDestw / $iDesth) >= ($oSource->width / $oSource->height)) {
				$iWidth = ($oSource->width / $oSource->height) * $iDesth;
				$iDestx += ($iDestw - $iWidth) / 2;
				$iDestw = $iWidth;
			} else {
				$iHight = (($oSource->height / $oSource->width)) * $iDestw;
				$iDesty += ($iDesth - $iHight) / 2;
				$iDesth = $iHight;
			}
		}
		array_push ( $resizeAgrv, $iDestx, $iDesty, $iSourcex, $iSourcey );
		array_push ( $resizeAgrv, $iDestw, $iDesth, $iSourcew, $iSourceh );
		return call_user_func_array ( 'imagecopyresized', $resizeAgrv );
	}
	/**
	 * 取得图片资源宽高
	 *
	 * @param string $resourceName 资源名称
	 * @return object 对象的宽和高
	 */
	private function getSize($resourceName) {
		$sizeArr = new stdClass ();
		$sizeArr->width = imagesx ( $this->hImageReSource [$resourceName] ['handel'] );
		$sizeArr->height = imagesy ( $this->hImageReSource [$resourceName] ['handel'] );
		return $sizeArr;
	}
	/**
	 * 以下增加BMP图像支持
	 * 部分代码参考phpthumb
	 * 
	 */
	/**
	 * GD对象转换成BMP数据
	 *
	 * @param resource $resourceName GD对象句柄
	 * @param string $file 文件名，如果填写则输出到文件中
	 * @return bool 是否成功输出图片
	 */
	private function gd2bmp($resourceName, $file = null) { //gd输出到bmp
		$imageSize = $this->getSize ( $resourceName );
		$bmpdata = '';
		for($y = ($imageSize->height - 1); $y >= 0; $y --) {
			$thisline = '';
			for($x = 0; $x < $imageSize->width; $x ++) {
				$argb = @ImageColorsForIndex ( $this->hImageReSource [$resourceName] ['handel'], @ImageColorAt ( $this->hImageReSource [$resourceName] ['handel'], $x, $y ) );
				//$thisline .= chr($argb['blue']).chr($argb['green']).chr($argb['red']);
				$thisline .= chr ( $argb ['blue'] ) . chr ( $argb ['green'] ) . chr ( $argb ['red'] );
			}
			while ( strlen ( $thisline ) % 4 ) {
				$thisline .= "\x00";
			}
			$bmpdata .= $thisline;
		}
		$bmpSize = strlen ( $bmpdata ) + 14 + 40;
		// BITMAPFILEHEADER [14 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_62uq.asp
		$BITMAPFILEHEADER = 'BM'; // WORD    bfType;
		$BITMAPFILEHEADER .= $this->LittleEndian2String ( $bmpSize, 4 ); // DWORD   bfSize;
		$BITMAPFILEHEADER .= $this->LittleEndian2String ( 0, 2 ); // WORD    bfReserved1;
		$BITMAPFILEHEADER .= $this->LittleEndian2String ( 0, 2 ); // WORD    bfReserved2;
		$BITMAPFILEHEADER .= $this->LittleEndian2String ( 54, 4 ); // DWORD   bfOffBits;
		// BITMAPINFOHEADER - [40 bytes] http://msdn.microsoft.com/library/en-us/gdi/bitmaps_1rw2.asp
		$BITMAPINFOHEADER = $this->LittleEndian2String ( 40, 4 ); // DWORD  biSize;
		$BITMAPINFOHEADER .= $this->LittleEndian2String ( $imageSize->width, 4 ); // LONG   biWidth;
		$BITMAPINFOHEADER .= $this->LittleEndian2String ( $imageSize->height, 4 ); // LONG   biHeight;
		$BITMAPINFOHEADER .= $this->LittleEndian2String ( 1, 2 ); // WORD   biPlanes;
		$BITMAPINFOHEADER .= $this->LittleEndian2String ( 24, 2 ); // WORD   biBitCount;
		$BITMAPINFOHEADER .= $this->LittleEndian2String ( 0, 4 ); // DWORD  biCompression;
		$BITMAPINFOHEADER .= $this->LittleEndian2String ( 0, 4 ); // DWORD  biSizeImage;
		$BITMAPINFOHEADER .= $this->LittleEndian2String ( 2835, 4 ); // LONG   biXPelsPerMeter;
		$BITMAPINFOHEADER .= $this->LittleEndian2String ( 2835, 4 ); // LONG   biYPelsPerMeter;
		$BITMAPINFOHEADER .= $this->LittleEndian2String ( 0, 4 ); // DWORD  biClrUsed;
		$BITMAPINFOHEADER .= $this->LittleEndian2String ( 0, 4 ); // DWORD  biClrImportant;
		if (is_string ( $file )) {
			return file_put_contents ( $file, $BITMAPFILEHEADER . $BITMAPINFOHEADER . $bmpdata );
		} else {
			echo $BITMAPFILEHEADER . $BITMAPINFOHEADER . $bmpdata;
			return true;
		}
	}
	/**
	 * BMP图片转成GD内存对象
	 *
	 * @param binary $bmpData 二进制图片数据 
	 * @return resource GD对象
	 */
	private function bmp2gd($bmpData) {
		$ThisFileInfo = array ();
		if ($this->getid3_bmp ( $bmpData, $ThisFileInfo, true, true )) {
			$gd = $this->PlotPixelsGD ( $ThisFileInfo ['bmp'], $this->bTrueColor );
			return $gd;
		}
		return false;
	}
	private function getid3_bmp(&$BMPdata, &$ThisFileInfo, $ExtractPalette = false, $ExtractData = false) {
		// shortcuts
		$ThisFileInfo ['bmp'] ['header'] ['raw'] = array ();
		$thisfile_bmp = &$ThisFileInfo ['bmp'];
		$thisfile_bmp_header = &$thisfile_bmp ['header'];
		$thisfile_bmp_header_raw = &$thisfile_bmp_header ['raw'];
		// BITMAPFILEHEADER [14 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_62uq.asp
		// all versions
		// WORD    bfType;
		// DWORD   bfSize;
		// WORD    bfReserved1;
		// WORD    bfReserved2;
		// DWORD   bfOffBits;
		$offset = 0;
		$overalloffset = 0;
		$BMPheader = substr ( $BMPdata, $overalloffset, 14 + 40 );
		$overalloffset += (14 + 40);
		$thisfile_bmp_header_raw ['identifier'] = substr ( $BMPheader, $offset, 2 );
		$offset += 2;
		if ($thisfile_bmp_header_raw ['identifier'] != 'BM') {
			$ThisFileInfo ['error'] [] = 'Expecting "BM" at offset ' . intval ( @$ThisFileInfo ['avdataoffset'] ) . ', found "' . $thisfile_bmp_header_raw ['identifier'] . '"';
			unset ( $ThisFileInfo ['fileformat'] );
			unset ( $ThisFileInfo ['bmp'] );
			return false;
		}
		$thisfile_bmp_header_raw ['filesize'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
		$offset += 4;
		$thisfile_bmp_header_raw ['reserved1'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
		$offset += 2;
		$thisfile_bmp_header_raw ['reserved2'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
		$offset += 2;
		$thisfile_bmp_header_raw ['data_offset'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
		$offset += 4;
		$thisfile_bmp_header_raw ['header_size'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
		$offset += 4;
		// check if the hardcoded-to-1 "planes" is at offset 22 or 26
		$planes22 = $this->LittleEndian2Int ( substr ( $BMPheader, 22, 2 ) );
		$planes26 = $this->LittleEndian2Int ( substr ( $BMPheader, 26, 2 ) );
		if (($planes22 == 1) && ($planes26 != 1)) {
			$thisfile_bmp ['type_os'] = 'OS/2';
			$thisfile_bmp ['type_version'] = 1;
		} elseif (($planes26 == 1) && ($planes22 != 1)) {
			$thisfile_bmp ['type_os'] = 'Windows';
			$thisfile_bmp ['type_version'] = 1;
		} elseif ($thisfile_bmp_header_raw ['header_size'] == 12) {
			$thisfile_bmp ['type_os'] = 'OS/2';
			$thisfile_bmp ['type_version'] = 1;
		} elseif ($thisfile_bmp_header_raw ['header_size'] == 40) {
			$thisfile_bmp ['type_os'] = 'Windows';
			$thisfile_bmp ['type_version'] = 1;
		} elseif ($thisfile_bmp_header_raw ['header_size'] == 84) {
			$thisfile_bmp ['type_os'] = 'Windows';
			$thisfile_bmp ['type_version'] = 4;
		} elseif ($thisfile_bmp_header_raw ['header_size'] == 100) {
			$thisfile_bmp ['type_os'] = 'Windows';
			$thisfile_bmp ['type_version'] = 5;
		} else {
			$ThisFileInfo ['error'] [] = 'Unknown BMP subtype (or not a BMP file)';
			unset ( $ThisFileInfo ['fileformat'] );
			unset ( $ThisFileInfo ['bmp'] );
			return false;
		}
		$ThisFileInfo ['fileformat'] = 'bmp';
		$ThisFileInfo ['video'] ['dataformat'] = 'bmp';
		$ThisFileInfo ['video'] ['lossless'] = true;
		$ThisFileInfo ['video'] ['pixel_aspect_ratio'] = ( float ) 1;
		if ($thisfile_bmp ['type_os'] == 'OS/2') {
			// OS/2-format BMP
			// http://netghost.narod.ru/gff/graphics/summary/os2bmp.htm
			// DWORD  Size;             /* Size of this structure in bytes */
			// DWORD  Width;            /* Bitmap width in pixels */
			// DWORD  Height;           /* Bitmap height in pixel */
			// WORD   NumPlanes;        /* Number of bit planes (color depth) */
			// WORD   BitsPerPixel;     /* Number of bits per pixel per plane */
			$thisfile_bmp_header_raw ['width'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
			$offset += 2;
			$thisfile_bmp_header_raw ['height'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
			$offset += 2;
			$thisfile_bmp_header_raw ['planes'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
			$offset += 2;
			$thisfile_bmp_header_raw ['bits_per_pixel'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
			$offset += 2;
			$ThisFileInfo ['video'] ['resolution_x'] = $thisfile_bmp_header_raw ['width'];
			$ThisFileInfo ['video'] ['resolution_y'] = $thisfile_bmp_header_raw ['height'];
			$ThisFileInfo ['video'] ['codec'] = 'BI_RGB ' . $thisfile_bmp_header_raw ['bits_per_pixel'] . '-bit';
			$ThisFileInfo ['video'] ['bits_per_sample'] = $thisfile_bmp_header_raw ['bits_per_pixel'];
			if ($thisfile_bmp ['type_version'] >= 2) {
				// DWORD  Compression;      /* Bitmap compression scheme */
				// DWORD  ImageDataSize;    /* Size of bitmap data in bytes */
				// DWORD  XResolution;      /* X resolution of display device */
				// DWORD  YResolution;      /* Y resolution of display device */
				// DWORD  ColorsUsed;       /* Number of color table indices used */
				// DWORD  ColorsImportant;  /* Number of important color indices */
				// WORD   Units;            /* Type of units used to measure resolution */
				// WORD   Reserved;         /* Pad structure to 4-byte boundary */
				// WORD   Recording;        /* Recording algorithm */
				// WORD   Rendering;        /* Halftoning algorithm used */
				// DWORD  Size1;            /* Reserved for halftoning algorithm use */
				// DWORD  Size2;            /* Reserved for halftoning algorithm use */
				// DWORD  ColorEncoding;    /* Color model used in bitmap */
				// DWORD  Identifier;       /* Reserved for application use */
				$thisfile_bmp_header_raw ['compression'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['bmp_data_size'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['resolution_h'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['resolution_v'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['colors_used'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['colors_important'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['resolution_units'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
				$offset += 2;
				$thisfile_bmp_header_raw ['reserved1'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
				$offset += 2;
				$thisfile_bmp_header_raw ['recording'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
				$offset += 2;
				$thisfile_bmp_header_raw ['rendering'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
				$offset += 2;
				$thisfile_bmp_header_raw ['size1'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['size2'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['color_encoding'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['identifier'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header ['compression'] = $this->BMPcompressionOS2Lookup ( $thisfile_bmp_header_raw ['compression'] );
				$ThisFileInfo ['video'] ['codec'] = $thisfile_bmp_header ['compression'] . ' ' . $thisfile_bmp_header_raw ['bits_per_pixel'] . '-bit';
			}
		} elseif ($thisfile_bmp ['type_os'] == 'Windows') {
			// Windows-format BMP
			// BITMAPINFOHEADER - [40 bytes] http://msdn.microsoft.com/library/en-us/gdi/bitmaps_1rw2.asp
			// all versions
			// DWORD  biSize;
			// LONG   biWidth;
			// LONG   biHeight;
			// WORD   biPlanes;
			// WORD   biBitCount;
			// DWORD  biCompression;
			// DWORD  biSizeImage;
			// LONG   biXPelsPerMeter;
			// LONG   biYPelsPerMeter;
			// DWORD  biClrUsed;
			// DWORD  biClrImportant;
			$thisfile_bmp_header_raw ['width'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ), true );
			$offset += 4;
			$thisfile_bmp_header_raw ['height'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ), true );
			$offset += 4;
			$thisfile_bmp_header_raw ['planes'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
			$offset += 2;
			$thisfile_bmp_header_raw ['bits_per_pixel'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 2 ) );
			$offset += 2;
			$thisfile_bmp_header_raw ['compression'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
			$offset += 4;
			$thisfile_bmp_header_raw ['bmp_data_size'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
			$offset += 4;
			$thisfile_bmp_header_raw ['resolution_h'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ), true );
			$offset += 4;
			$thisfile_bmp_header_raw ['resolution_v'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ), true );
			$offset += 4;
			$thisfile_bmp_header_raw ['colors_used'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
			$offset += 4;
			$thisfile_bmp_header_raw ['colors_important'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
			$offset += 4;
			$thisfile_bmp_header ['compression'] = $this->BMPcompressionWindowsLookup ( $thisfile_bmp_header_raw ['compression'] );
			$ThisFileInfo ['video'] ['resolution_x'] = $thisfile_bmp_header_raw ['width'];
			$ThisFileInfo ['video'] ['resolution_y'] = $thisfile_bmp_header_raw ['height'];
			$ThisFileInfo ['video'] ['codec'] = $thisfile_bmp_header ['compression'] . ' ' . $thisfile_bmp_header_raw ['bits_per_pixel'] . '-bit';
			$ThisFileInfo ['video'] ['bits_per_sample'] = $thisfile_bmp_header_raw ['bits_per_pixel'];
			if (($thisfile_bmp ['type_version'] >= 4) || ($thisfile_bmp_header_raw ['compression'] == 3)) {
				// should only be v4+, but BMPs with type_version==1 and BI_BITFIELDS compression have been seen
				$BMPheader .= substr ( $BMPdata, $overalloffset, 44 );
				$overalloffset += 44;
				// BITMAPV4HEADER - [44 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_2k1e.asp
				// Win95+, WinNT4.0+
				// DWORD        bV4RedMask;
				// DWORD        bV4GreenMask;
				// DWORD        bV4BlueMask;
				// DWORD        bV4AlphaMask;
				// DWORD        bV4CSType;
				// CIEXYZTRIPLE bV4Endpoints;
				// DWORD        bV4GammaRed;
				// DWORD        bV4GammaGreen;
				// DWORD        bV4GammaBlue;
				$thisfile_bmp_header_raw ['red_mask'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['green_mask'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['blue_mask'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['alpha_mask'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['cs_type'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['ciexyz_red'] = substr ( $BMPheader, $offset, 4 );
				$offset += 4;
				$thisfile_bmp_header_raw ['ciexyz_green'] = substr ( $BMPheader, $offset, 4 );
				$offset += 4;
				$thisfile_bmp_header_raw ['ciexyz_blue'] = substr ( $BMPheader, $offset, 4 );
				$offset += 4;
				$thisfile_bmp_header_raw ['gamma_red'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['gamma_green'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['gamma_blue'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header ['ciexyz_red'] = $this->FixedPoint2_30 ( strrev ( $thisfile_bmp_header_raw ['ciexyz_red'] ) );
				$thisfile_bmp_header ['ciexyz_green'] = $this->FixedPoint2_30 ( strrev ( $thisfile_bmp_header_raw ['ciexyz_green'] ) );
				$thisfile_bmp_header ['ciexyz_blue'] = $this->FixedPoint2_30 ( strrev ( $thisfile_bmp_header_raw ['ciexyz_blue'] ) );
			}
			if ($thisfile_bmp ['type_version'] >= 5) {
				$BMPheader .= substr ( $BMPdata, $overalloffset, 16 );
				$overalloffset += 16;
				// BITMAPV5HEADER - [16 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_7c36.asp
				// Win98+, Win2000+
				// DWORD        bV5Intent;
				// DWORD        bV5ProfileData;
				// DWORD        bV5ProfileSize;
				// DWORD        bV5Reserved;
				$thisfile_bmp_header_raw ['intent'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['profile_data_offset'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['profile_data_size'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
				$thisfile_bmp_header_raw ['reserved3'] = $this->LittleEndian2Int ( substr ( $BMPheader, $offset, 4 ) );
				$offset += 4;
			}
		} else {
			$ThisFileInfo ['error'] [] = 'Unknown BMP format in header.';
			return false;
		}
		if ($ExtractPalette || $ExtractData) {
			$PaletteEntries = 0;
			if ($thisfile_bmp_header_raw ['bits_per_pixel'] < 16) {
				$PaletteEntries = pow ( 2, $thisfile_bmp_header_raw ['bits_per_pixel'] );
			} elseif (isset ( $thisfile_bmp_header_raw ['colors_used'] ) && ($thisfile_bmp_header_raw ['colors_used'] > 0) && ($thisfile_bmp_header_raw ['colors_used'] <= 256)) {
				$PaletteEntries = $thisfile_bmp_header_raw ['colors_used'];
			}
			if ($PaletteEntries > 0) {
				$BMPpalette = substr ( $BMPdata, $overalloffset, 4 * $PaletteEntries );
				$overalloffset += 4 * $PaletteEntries;
				$paletteoffset = 0;
				for($i = 0; $i < $PaletteEntries; $i ++) {
					// RGBQUAD          - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_5f8y.asp
					// BYTE    rgbBlue;
					// BYTE    rgbGreen;
					// BYTE    rgbRed;
					// BYTE    rgbReserved;
					$blue = $this->LittleEndian2Int ( substr ( $BMPpalette, $paletteoffset ++, 1 ) );
					$green = $this->LittleEndian2Int ( substr ( $BMPpalette, $paletteoffset ++, 1 ) );
					$red = $this->LittleEndian2Int ( substr ( $BMPpalette, $paletteoffset ++, 1 ) );
					if (($thisfile_bmp ['type_os'] == 'OS/2') && ($thisfile_bmp ['type_version'] == 1)) {
						// no padding byte
					} else {
						$paletteoffset ++; // padding byte
					}
					$thisfile_bmp ['palette'] [$i] = (($red << 16) | ($green << 8) | ($blue));
				}
			}
		}
		if ($ExtractData) {
			$RowByteLength = ceil ( ($thisfile_bmp_header_raw ['width'] * ($thisfile_bmp_header_raw ['bits_per_pixel'] / 8)) / 4 ) * 4; // round up to nearest DWORD boundry
			$BMPpixelData = substr ( $BMPdata, $thisfile_bmp_header_raw ['data_offset'], $thisfile_bmp_header_raw ['height'] * $RowByteLength );
			$overalloffset = $thisfile_bmp_header_raw ['data_offset'] + ($thisfile_bmp_header_raw ['height'] * $RowByteLength);
			$pixeldataoffset = 0;
			switch (@$thisfile_bmp_header_raw ['compression']) {
				case 0 : // BI_RGB
					switch ($thisfile_bmp_header_raw ['bits_per_pixel']) {
						case 1 :
							for($row = ($thisfile_bmp_header_raw ['height'] - 1); $row >= 0; $row --) {
								for($col = 0; $col < $thisfile_bmp_header_raw ['width']; ) {
									$paletteindexbyte = ord ( $BMPpixelData {$pixeldataoffset ++} );
									for($i = 7; $i >= 0; $i --) {
										$paletteindex = ($paletteindexbyte & (0x01 << $i)) >> $i;
										$thisfile_bmp ['data'] [$row] [$col] = $thisfile_bmp ['palette'] [$paletteindex];
										$col ++;
									}
								}
								while ( ($pixeldataoffset % 4) != 0 ) {
									// lines are padded to nearest DWORD
									$pixeldataoffset ++;
								}
							}
							break;
						case 4 :
							for($row = ($thisfile_bmp_header_raw ['height'] - 1); $row >= 0; $row --) {
								for($col = 0; $col < $thisfile_bmp_header_raw ['width'];) {
									$paletteindexbyte = ord ( $BMPpixelData {$pixeldataoffset ++} );
									for($i = 1; $i >= 0; $i --) {
										$paletteindex = ($paletteindexbyte & (0x0F << (4 * $i))) >> (4 * $i);
										$thisfile_bmp ['data'] [$row] [$col] = $thisfile_bmp ['palette'] [$paletteindex];
										$col ++;
									}
								}
								while ( ($pixeldataoffset % 4) != 0 ) {
									// lines are padded to nearest DWORD
									$pixeldataoffset ++;
								}
							}
							break;
						case 8 :
							for($row = ($thisfile_bmp_header_raw ['height'] - 1); $row >= 0; $row --) {
								for($col = 0; $col < $thisfile_bmp_header_raw ['width']; $col ++) {
									$paletteindex = ord ( $BMPpixelData {$pixeldataoffset ++} );
									$thisfile_bmp ['data'] [$row] [$col] = $thisfile_bmp ['palette'] [$paletteindex];
								}
								while ( ($pixeldataoffset % 4) != 0 ) {
									// lines are padded to nearest DWORD
									$pixeldataoffset ++;
								}
							}
							break;
						case 24 :
							for($row = ($thisfile_bmp_header_raw ['height'] - 1); $row >= 0; $row --) {
								for($col = 0; $col < $thisfile_bmp_header_raw ['width']; $col ++) {
									$thisfile_bmp ['data'] [$row] [$col] = (ord ( $BMPpixelData {$pixeldataoffset + 2} ) << 16) | (ord ( $BMPpixelData {$pixeldataoffset + 1} ) << 8) | ord ( $BMPpixelData {$pixeldataoffset} );
									$pixeldataoffset += 3;
								}
								while ( ($pixeldataoffset % 4) != 0 ) {
									// lines are padded to nearest DWORD
									$pixeldataoffset ++;
								}
							}
							break;
						case 32 :
							for($row = ($thisfile_bmp_header_raw ['height'] - 1); $row >= 0; $row --) {
								for($col = 0; $col < $thisfile_bmp_header_raw ['width']; $col ++) {
									$thisfile_bmp ['data'] [$row] [$col] = (ord ( $BMPpixelData {$pixeldataoffset + 3} ) << 24) | (ord ( $BMPpixelData {$pixeldataoffset + 2} ) << 16) | (ord ( $BMPpixelData {$pixeldataoffset + 1} ) << 8) | ord ( $BMPpixelData {$pixeldataoffset} );
									$pixeldataoffset += 4;
								}
								while ( ($pixeldataoffset % 4) != 0 ) {
									// lines are padded to nearest DWORD
									$pixeldataoffset ++;
								}
							}
							break;
						case 16 :
							// ?
							break;
						default :
							$ThisFileInfo ['error'] [] = 'Unknown bits-per-pixel value (' . $thisfile_bmp_header_raw ['bits_per_pixel'] . ') - cannot read pixel data';
							break;
					}
					break;
				case 1 : // BI_RLE8 - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_6x0u.asp
					switch ($thisfile_bmp_header_raw ['bits_per_pixel']) {
						case 8 :
							$pixelcounter = 0;
							while ( $pixeldataoffset < strlen ( $BMPpixelData ) ) {
								$firstbyte = $this->LittleEndian2Int ( substr ( $BMPpixelData, $pixeldataoffset ++, 1 ) );
								$secondbyte = $this->LittleEndian2Int ( substr ( $BMPpixelData, $pixeldataoffset ++, 1 ) );
								if ($firstbyte == 0) {
									// escaped/absolute mode - the first byte of the pair can be set to zero to
									// indicate an escape character that denotes the end of a line, the end of
									// a bitmap, or a delta, depending on the value of the second byte.
									switch ($secondbyte) {
										case 0 :
											// end of line
											// no need for special processing, just ignore
											break;
										case 1 :
											// end of bitmap
											$pixeldataoffset = strlen ( $BMPpixelData ); // force to exit loop just in case
											break;
										case 2 :
											// delta - The 2 bytes following the escape contain unsigned values
											// indicating the horizontal and vertical offsets of the next pixel
											// from the current position.
											$colincrement = $this->LittleEndian2Int ( substr ( $BMPpixelData, $pixeldataoffset ++, 1 ) );
											$rowincrement = $this->LittleEndian2Int ( substr ( $BMPpixelData, $pixeldataoffset ++, 1 ) );
											$col = ($pixelcounter % $thisfile_bmp_header_raw ['width']) + $colincrement;
											$row = ($thisfile_bmp_header_raw ['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw ['width'])) - $rowincrement;
											$pixelcounter = ($row * $thisfile_bmp_header_raw ['width']) + $col;
											break;
										default :
											// In absolute mode, the first byte is zero and the second byte is a
											// value in the range 03H through FFH. The second byte represents the
											// number of bytes that follow, each of which contains the color index
											// of a single pixel. Each run must be aligned on a word boundary.
											for($i = 0; $i < $secondbyte; $i ++) {
												$paletteindex = $this->LittleEndian2Int ( substr ( $BMPpixelData, $pixeldataoffset ++, 1 ) );
												$col = $pixelcounter % $thisfile_bmp_header_raw ['width'];
												$row = $thisfile_bmp_header_raw ['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw ['width']);
												$thisfile_bmp ['data'] [$row] [$col] = $thisfile_bmp ['palette'] [$paletteindex];
												$pixelcounter ++;
											}
											while ( ($pixeldataoffset % 2) != 0 ) {
												// Each run must be aligned on a word boundary.
												$pixeldataoffset ++;
											}
											break;
									}
								} else {
									// encoded mode - the first byte specifies the number of consecutive pixels
									// to be drawn using the color index contained in the second byte.
									for($i = 0; $i < $firstbyte; $i ++) {
										$col = $pixelcounter % $thisfile_bmp_header_raw ['width'];
										$row = $thisfile_bmp_header_raw ['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw ['width']);
										$thisfile_bmp ['data'] [$row] [$col] = $thisfile_bmp ['palette'] [$secondbyte];
										$pixelcounter ++;
									}
								}
							}
							break;
						default :
							$ThisFileInfo ['error'] [] = 'Unknown bits-per-pixel value (' . $thisfile_bmp_header_raw ['bits_per_pixel'] . ') - cannot read pixel data';
							break;
					}
					break;
				case 2 : // BI_RLE4 - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_6x0u.asp
					switch ($thisfile_bmp_header_raw ['bits_per_pixel']) {
						case 4 :
							$pixelcounter = 0;
							while ( $pixeldataoffset < strlen ( $BMPpixelData ) ) {
								$firstbyte = $this->LittleEndian2Int ( substr ( $BMPpixelData, $pixeldataoffset ++, 1 ) );
								$secondbyte = $this->LittleEndian2Int ( substr ( $BMPpixelData, $pixeldataoffset ++, 1 ) );
								if ($firstbyte == 0) {
									// escaped/absolute mode - the first byte of the pair can be set to zero to
									// indicate an escape character that denotes the end of a line, the end of
									// a bitmap, or a delta, depending on the value of the second byte.
									switch ($secondbyte) {
										case 0 :
											// end of line
											// no need for special processing, just ignore
											break;
										case 1 :
											// end of bitmap
											$pixeldataoffset = strlen ( $BMPpixelData ); // force to exit loop just in case
											break;
										case 2 :
											// delta - The 2 bytes following the escape contain unsigned values
											// indicating the horizontal and vertical offsets of the next pixel
											// from the current position.
											$colincrement = $this->LittleEndian2Int ( substr ( $BMPpixelData, $pixeldataoffset ++, 1 ) );
											$rowincrement = $this->LittleEndian2Int ( substr ( $BMPpixelData, $pixeldataoffset ++, 1 ) );
											$col = ($pixelcounter % $thisfile_bmp_header_raw ['width']) + $colincrement;
											$row = ($thisfile_bmp_header_raw ['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw ['width'])) - $rowincrement;
											$pixelcounter = ($row * $thisfile_bmp_header_raw ['width']) + $col;
											break;
										default :
											// In absolute mode, the first byte is zero. The second byte contains the number
											// of color indexes that follow. Subsequent bytes contain color indexes in their
											// high- and low-order 4 bits, one color index for each pixel. In absolute mode,
											// each run must be aligned on a word boundary.
											for($i = 0; $i < ceil ( $secondbyte / 2 ); $i ++) {
												$paletteindexbyte = $this->LittleEndian2Int ( substr ( $BMPpixelData, $pixeldataoffset ++, 1 ) );
												$paletteindexes [] = ($paletteindexbyte & 0xF0) >> 4;
												$paletteindexes [] = ($paletteindexbyte & 0x0F);
											}
											while ( ($pixeldataoffset % 2) != 0 ) {
												// Each run must be aligned on a word boundary.
												$pixeldataoffset ++;
											}
											foreach ( $paletteindexes as $paletteindex ) {
												$col = $pixelcounter % $thisfile_bmp_header_raw ['width'];
												$row = $thisfile_bmp_header_raw ['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw ['width']);
												$thisfile_bmp ['data'] [$row] [$col] = $thisfile_bmp ['palette'] [$paletteindex];
												$pixelcounter ++;
											}
											break;
									}
								} else {
									// encoded mode - the first byte of the pair contains the number of pixels to be
									// drawn using the color indexes in the second byte. The second byte contains two
									// color indexes, one in its high-order 4 bits and one in its low-order 4 bits.
									// The first of the pixels is drawn using the color specified by the high-order
									// 4 bits, the second is drawn using the color in the low-order 4 bits, the third
									// is drawn using the color in the high-order 4 bits, and so on, until all the
									// pixels specified by the first byte have been drawn.
									$paletteindexes [0] = ($secondbyte & 0xF0) >> 4;
									$paletteindexes [1] = ($secondbyte & 0x0F);
									for($i = 0; $i < $firstbyte; $i ++) {
										$col = $pixelcounter % $thisfile_bmp_header_raw ['width'];
										$row = $thisfile_bmp_header_raw ['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw ['width']);
										$thisfile_bmp ['data'] [$row] [$col] = $thisfile_bmp ['palette'] [$paletteindexes [($i % 2)]];
										$pixelcounter ++;
									}
								}
							}
							break;
						default :
							$ThisFileInfo ['error'] [] = 'Unknown bits-per-pixel value (' . $thisfile_bmp_header_raw ['bits_per_pixel'] . ') - cannot read pixel data';
							break;
					}
					break;
				case 3 : // BI_BITFIELDS
					switch ($thisfile_bmp_header_raw ['bits_per_pixel']) {
						case 16 :
						case 32 :
							$redshift = 0;
							$greenshift = 0;
							$blueshift = 0;
							if (! $thisfile_bmp_header_raw ['red_mask'] || ! $thisfile_bmp_header_raw ['green_mask'] || ! $thisfile_bmp_header_raw ['blue_mask']) {
								$ThisFileInfo ['error'] [] = 'missing $thisfile_bmp_header_raw[(red|green|blue)_mask]';
								return false;
							}
							while ( (($thisfile_bmp_header_raw ['red_mask'] >> $redshift) & 0x01) == 0 ) {
								$redshift ++;
							}
							while ( (($thisfile_bmp_header_raw ['green_mask'] >> $greenshift) & 0x01) == 0 ) {
								$greenshift ++;
							}
							while ( (($thisfile_bmp_header_raw ['blue_mask'] >> $blueshift) & 0x01) == 0 ) {
								$blueshift ++;
							}
							for($row = ($thisfile_bmp_header_raw ['height'] - 1); $row >= 0; $row --) {
								for($col = 0; $col < $thisfile_bmp_header_raw ['width']; $col ++) {
									$pixelvalue = $this->LittleEndian2Int ( substr ( $BMPpixelData, $pixeldataoffset, $thisfile_bmp_header_raw ['bits_per_pixel'] / 8 ) );
									$pixeldataoffset += $thisfile_bmp_header_raw ['bits_per_pixel'] / 8;
									$red = intval ( round ( ((($pixelvalue & $thisfile_bmp_header_raw ['red_mask']) >> $redshift) / ($thisfile_bmp_header_raw ['red_mask'] >> $redshift)) * 255 ) );
									$green = intval ( round ( ((($pixelvalue & $thisfile_bmp_header_raw ['green_mask']) >> $greenshift) / ($thisfile_bmp_header_raw ['green_mask'] >> $greenshift)) * 255 ) );
									$blue = intval ( round ( ((($pixelvalue & $thisfile_bmp_header_raw ['blue_mask']) >> $blueshift) / ($thisfile_bmp_header_raw ['blue_mask'] >> $blueshift)) * 255 ) );
									$thisfile_bmp ['data'] [$row] [$col] = (($red << 16) | ($green << 8) | ($blue));
								}
								while ( ($pixeldataoffset % 4) != 0 ) {
									// lines are padded to nearest DWORD
									$pixeldataoffset ++;
								}
							}
							break;
						default :
							$ThisFileInfo ['error'] [] = 'Unknown bits-per-pixel value (' . $thisfile_bmp_header_raw ['bits_per_pixel'] . ') - cannot read pixel data';
							break;
					}
					break;
				default : // unhandled compression type
					$ThisFileInfo ['error'] [] = 'Unknown/unhandled compression type value (' . $thisfile_bmp_header_raw ['compression'] . ') - cannot decompress pixel data';
					break;
			}
		}
		return true;
	}
	private function PlotPixelsGD(&$BMPdata, $truecolor = true) {
		$imagewidth = $BMPdata ['header'] ['raw'] ['width'];
		$imageheight = $BMPdata ['header'] ['raw'] ['height'];
		if ($this->bTrueColor) {
			$gd = @ImageCreateTrueColor ( $imagewidth, $imageheight );
		} else {
			$gd = @ImageCreate ( $imagewidth, $imageheight );
			if (! empty ( $BMPdata ['palette'] )) {
				// create GD palette from BMP palette
				foreach ( $BMPdata ['palette'] as $color ) {
					list ( $r, $g, $b ) = $this->IntColor2RGB ( $color );
					ImageColorAllocate ( $gd, $r, $g, $b );
				}
			} else {
				// create 216-color websafe palette
				for($r = 0x00; $r <= 0xFF; $r += 0x33) {
					for($g = 0x00; $g <= 0xFF; $g += 0x33) {
						for($b = 0x00; $b <= 0xFF; $b += 0x33) {
							ImageColorAllocate ( $gd, $r, $g, $b );
						}
					}
				}
			}
		}
		if (! is_resource ( $gd )) {
			return false;
		}
		foreach ( $BMPdata ['data'] as $row => $colarray ) {
			set_time_limit ( 30 );
			foreach ( $colarray as $col => $color ) {
				list ( $red, $green, $blue ) = $this->IntColor2RGB ( $color );
				if ($truecolor) {
					$pixelcolor = ImageColorAllocate ( $gd, $red, $green, $blue );
				} else {
					$pixelcolor = ImageColorClosest ( $gd, $red, $green, $blue );
				}
				ImageSetPixel ( $gd, $col, $row, $pixelcolor );
			}
		}
		return $gd;
	}
	private function LittleEndian2Int($byteword) {
		$intvalue = 0;
		$byteword = strrev ( $byteword );
		$bytewordlen = strlen ( $byteword );
		for($i = 0; $i < $bytewordlen; $i ++) {
			$intvalue += ord ( $byteword {$i} ) * pow ( 256, ($bytewordlen - 1 - $i) );
		}
		return $intvalue;
	}
	private function LittleEndian2String($number, $minbytes = 1) {
		$intstring = '';
		while ( $number > 0 ) {
			$intstring = $intstring . chr ( $number & 255 );
			$number >>= 8;
		}
		return str_pad ( $intstring, $minbytes, "\x00", STR_PAD_RIGHT );
	}
	private function BMPcompressionWindowsLookup($compressionid) {
		static $BMPcompressionWindowsLookup = array (0 => 'BI_RGB', 1 => 'BI_RLE8', 2 => 'BI_RLE4', 3 => 'BI_BITFIELDS', 4 => 'BI_JPEG', 5 => 'BI_PNG' );
		return (isset ( $BMPcompressionWindowsLookup [$compressionid] ) ? $BMPcompressionWindowsLookup [$compressionid] : 'invalid');
	}
	private function BMPcompressionOS2Lookup($compressionid) {
		static $BMPcompressionOS2Lookup = array (0 => 'BI_RGB', 1 => 'BI_RLE8', 2 => 'BI_RLE4', 3 => 'Huffman 1D', 4 => 'BI_RLE24' );
		return (isset ( $BMPcompressionOS2Lookup [$compressionid] ) ? $BMPcompressionOS2Lookup [$compressionid] : 'invalid');
	}
	private function IntColor2RGB($color) {
		$red = ($color & 0x00FF0000) >> 16;
		$green = ($color & 0x0000FF00) >> 8;
		$blue = ($color & 0x000000FF);
		return array ($red, $green, $blue );
	}
	/**
	 * BMP图像支持结束
	 */
	/**
	 * 输出图片
	 *
	 * @param string $type 文件类型
	 * @param string $file 保存为文件名
	 * @param int $quality 品质只有jpeg有效
	 * @param bool $interlace 是否输出隔行扫描的文件，只有jpeg格式有效
	 */
	public function output($type = "jpg", $file = null, $quality = 75, $interlace = false) {
		switch (strtolower ( $type )) {
			case 'jpeg' :
			case 'jpg' :
				if ($interlace) {
					imageinterlace ( $this->hImageReSource ['mast'] ['handel'], true );
				}
				if (! $file) {
					header ( "Content/type: image/jpeg" );
				}
				imagejpeg ( $this->hImageReSource ['mast'] ['handel'], $file, $quality );
				break;
			case 'png' :
				if (! $file) {
					header ( "Content/type: image/png" );
				}
				imagepng ( $this->hImageReSource ['mast'] ['handel'], $file );
				break;
			case 'gif' :
				if (! $file) {
					header ( "Content/type: image/gif" );
				}
				imagegif ( $this->hImageReSource ['mast'] ['handel'], $file );
				break;
			case 'bmp' :
				if (! $file) {
					header ( "Content/type: image/bmp" );
				}
				$this->gd2bmp ( 'mast', $file );
				break;
			case 'wbmp' :
				if (! $file) {
					header ( "Content/type: image/vnd.wap.wbmp" );
				}
				imagewbmp ( $this->hImageReSource ['mast'] ['handel'], $file );
				break;
			default :
				break;
		}
	}
	/**
	 * 返回本模块信息
	 *
	 * @return string
	 */
	public function printInfo() {
		$version = '$Revision: 122 $';
		$moudle = __CLASS__;
		$return = '';
		$return .= startTable ();
		$return .= printRow ( array (array ('class' => 'h', 'content' => '<center>' . $moudle . '</center>', 'colspan' => '2' ) ) );
		$return .= printRow ( array (array ('class' => 'e', 'content' => 'author' ), array ('class' => 'v', 'content' => 'glzaboy' ) ) );
		$return .= printRow ( array (array ('class' => 'e', 'content' => 'version' ), array ('class' => 'v', 'content' => $version ) ) );
		$return .= printRow ( array (array ('class' => 'e', 'content' => 'Current GD version' ), array ('class' => 'v', 'content' => GD_VERSION ) ) );
		$return .= printRow ( array (array ('class' => 'e', 'content' => 'Dependence' ), array ('class' => 'v', 'content' => 'GD2' ) ) );
		$return .= printRow ( array (array ('class' => 'e', 'content' => 'Notice' ), array ('class' => 'v', 'content' => 'bmp suport by phpthumb,nfo suport by nfo2pic' ) ) );
		$return .= printRow ( array (array ('class' => 'e', 'content' => 'Input Support' ), array ('class' => 'v', 'content' => 'jpg,gif,png,xbm,wbmp,bmp,nfo' ) ) );
		$return .= printRow ( array (array ('class' => 'e', 'content' => 'Ooutput Support' ), array ('class' => 'v', 'content' => 'jpg,gif,png,bmp,wbmp' ) ) );
		$return .= endTable ();
		return $return;
	}
}